/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package manager.modulo.ordemservico.fonte;

import java.sql.SQLException;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import manager.auxiliares.*;
import manager.helpers.validation.FormatedFieldValidator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.modulo.ordemservico.dao.*;
import manager.modulo.ordemservico.enumerator.EnumEpi.Epi;
import manager.modulo.ordemservico.enumerator.EnumRisco.Risco;
import manager.principal.fonte.JanelaLogin;

/**
 *
 * @author THIAGO
 */
public class JanelaProcedimento extends javax.swing.JFrame {

    int idProcedimento = 0;

    /**
     * Creates new form JanelaOrdemServico
     */
    public JanelaProcedimento() {
        initComponents();
    }

    /**
     * Creates new form UserWindow
     */
    public JanelaProcedimento(int novoIdOrdemServico) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idProcedimento = novoIdOrdemServico;
            configureWindow();
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }

    private void setEntityInformations() {
        jButton2.setText("Editar");
        jButton2.setIcon(new Icons().getEdit());
        try {
            ProcedimentoDao procedimentoDao = new ProcedimentoDao();
            procedimentoDao.buscar(idProcedimento);
            jTextField2.setText(procedimentoDao.getNome());
            jFormattedTextField2.setValue(procedimentoDao.getValor()/100);
            jTextArea1.setText(procedimentoDao.getDescricao());

            LinkedList<Integer> listaRisco = ProcedimentoRiscoDao.buscarListaIdRiscoPorProcedimento(idProcedimento);
            RiscoDao riscoDao = new RiscoDao();
            for (int i = 0; i < listaRisco.size(); i++) {
                riscoDao.buscar(listaRisco.get(i));
                switch (riscoDao.getIdentificador()) {
                    case CHOQUE:
                        jCheckBox2.setSelected(true);
                        break;
                    case QUEDA:
                        jCheckBox4.setSelected(true);
                        break;
                    case QUEDAOBJETO:
                        jCheckBox5.setSelected(true);
                        break;
                    case QUEIMADURA:
                        jCheckBox3.setSelected(true);
                        break;
                }
            }

            LinkedList<Integer> listaEpi = ProcedimentoEpiDao.buscarListaIdEpiPorProcedimento(idProcedimento);
            EpiDao epiDao = new EpiDao();
            for (int i = 0; i < listaEpi.size(); i++) {
                epiDao.buscar(listaEpi.get(i));
                switch (epiDao.getIdentificador()) {
                    case BOTA:
                        jCheckBox6.setSelected(true);
                        break;
                    case CINTO:
                        jCheckBox7.setSelected(true);
                        break;
                    case LUVA:
                        jCheckBox8.setSelected(true);
                        break;
                    case OCULOS:
                        jCheckBox9.setSelected(true);
                        break;
                    case CAPACETE:
                        jCheckBox10.setSelected(true);
                        break;
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Procedimento");
        }
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configureWindow() throws SQLException {
        if (idProcedimento != 0) { // Edição de usuário
            setEntityInformations();
        }
        checkRequiredFields();
    }

    private LinkedList<String> validarCamposOrdemServico() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField2).validarCampo()) {
            fieldList.add(((TextFieldValidator) jTextField2).getjLabel().getText());
        }
        if (!((FormatedFieldValidator) jFormattedTextField2).validarCampo()) {
            fieldList.add(((FormatedFieldValidator) jFormattedTextField2).getjLabel().getText());
        }
        return fieldList;
    }

    private int adicionarProcedimento() {
        try {
            try {
                if (ProcedimentoDao.buscarIdProcedimentoPorNome(jTextField2.getText()) == 0) {

                    JanelaLogin.connection.setAutoCommit(false);

                    ProcedimentoDao procedimentoDao = new ProcedimentoDao();
                    procedimentoDao.setNome(jTextField2.getText());
                    procedimentoDao.setValor((int) (((Number) jFormattedTextField2.getValue()).doubleValue() * 100));
                    procedimentoDao.setDescricao(jTextArea1.getText());
                    procedimentoDao.inserir();

                    ProcedimentoRiscoDao procedimentoRiscoDao = new ProcedimentoRiscoDao();
                    procedimentoRiscoDao.setIdProcedimento(procedimentoDao.getId());
                    /**
                     * RISCOS
                     */
                    if (jCheckBox2.isSelected()) {//CHOQUE
                        procedimentoRiscoDao.setIdRisco(RiscoDao.buscarIdRiscoPorIdentificador(Risco.CHOQUE));
                        procedimentoRiscoDao.inserir();
                    }

                    if (jCheckBox4.isSelected()) {//QUEDA
                        procedimentoRiscoDao.setIdRisco(RiscoDao.buscarIdRiscoPorIdentificador(Risco.QUEDA));
                        procedimentoRiscoDao.inserir();
                    }

                    if (jCheckBox5.isSelected()) {//QUEDA OBJETOS
                        procedimentoRiscoDao.setIdRisco(RiscoDao.buscarIdRiscoPorIdentificador(Risco.QUEDAOBJETO));
                        procedimentoRiscoDao.inserir();
                    }

                    if (jCheckBox3.isSelected()) {//QUEIMADURA
                        procedimentoRiscoDao.setIdRisco(RiscoDao.buscarIdRiscoPorIdentificador(Risco.QUEIMADURA));
                        procedimentoRiscoDao.inserir();
                    }


                    ProcedimentoEpiDao procedimentoEpiDao = new ProcedimentoEpiDao();
                    procedimentoEpiDao.setIdProcedimento(procedimentoDao.getId());

                    /**
                     * EPIS
                     */
                    if (jCheckBox6.isSelected()) {//BOTA
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.BOTA));
                        procedimentoEpiDao.inserir();
                    }

                    if (jCheckBox7.isSelected()) {//CINTO
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.CINTO));
                        procedimentoEpiDao.inserir();
                    }

                    if (jCheckBox8.isSelected()) {//LUVA
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.LUVA));
                        procedimentoEpiDao.inserir();
                    }

                    if (jCheckBox9.isSelected()) {//OCULOS
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.OCULOS));
                        procedimentoEpiDao.inserir();
                    }

                    if (jCheckBox10.isSelected()) {//CAPACETE
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.CAPACETE));
                        procedimentoEpiDao.inserir();
                    }

                    JanelaLogin.connection.commit();

                    JOptionPane.showMessageDialog(null, "Procedimento cadastrado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                } else {
                    JOptionPane.showMessageDialog(null, "Este procedimento já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }

        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
        return 0;
    }

    private void editarProcedimento() {
        try {
            ProcedimentoDao procedimentoDao = new ProcedimentoDao();
            procedimentoDao.buscar(idProcedimento);
            if (ProcedimentoDao.buscarIdProcedimentoPorNome(jTextField2.getText()) == 0 || procedimentoDao.getNome().equalsIgnoreCase(jTextField2.getText())) {
                try {
                    JanelaLogin.connection.setAutoCommit(false);

                    procedimentoDao.setNome(jTextField2.getText());
                    procedimentoDao.setValor((int) (((Number) jFormattedTextField2.getValue()).doubleValue() * 100));
                    procedimentoDao.setDescricao(jTextArea1.getText());
                    procedimentoDao.atualizar();

                    ProcedimentoRiscoDao procedimentoRiscoDao = new ProcedimentoRiscoDao();
                    procedimentoRiscoDao.setIdProcedimento(procedimentoDao.getId());
                    procedimentoRiscoDao.deletar();
                    /**
                     * RISCOS
                     */
                    if (jCheckBox2.isSelected()) {//CHOQUE
                        procedimentoRiscoDao.setIdRisco(RiscoDao.buscarIdRiscoPorIdentificador(Risco.CHOQUE));
                        procedimentoRiscoDao.inserir();
                    }

                    if (jCheckBox4.isSelected()) {//QUEDA
                        procedimentoRiscoDao.setIdRisco(RiscoDao.buscarIdRiscoPorIdentificador(Risco.QUEDA));
                        procedimentoRiscoDao.inserir();
                    }

                    if (jCheckBox5.isSelected()) {//QUEDA OBJETOS
                        procedimentoRiscoDao.setIdRisco(RiscoDao.buscarIdRiscoPorIdentificador(Risco.QUEDAOBJETO));
                        procedimentoRiscoDao.inserir();
                    }

                    if (jCheckBox3.isSelected()) {//QUEIMADURA
                        procedimentoRiscoDao.setIdRisco(RiscoDao.buscarIdRiscoPorIdentificador(Risco.QUEIMADURA));
                        procedimentoRiscoDao.inserir();
                    }


                    ProcedimentoEpiDao procedimentoEpiDao = new ProcedimentoEpiDao();
                    procedimentoEpiDao.setIdProcedimento(procedimentoDao.getId());
                    procedimentoEpiDao.deletar();

                    /**
                     * EPIS
                     */
                    if (jCheckBox6.isSelected()) {//BOTA
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.BOTA));
                        procedimentoEpiDao.inserir();
                    }

                    if (jCheckBox7.isSelected()) {//CINTO
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.CINTO));
                        procedimentoEpiDao.inserir();
                    }

                    if (jCheckBox8.isSelected()) {//LUVA
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.LUVA));
                        procedimentoEpiDao.inserir();
                    }

                    if (jCheckBox9.isSelected()) {//OCULOS
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.OCULOS));
                        procedimentoEpiDao.inserir();
                    }

                    if (jCheckBox10.isSelected()) {//CAPACETE
                        procedimentoEpiDao.setIdEpi(EpiDao.buscarIdEpiPorIdentificador(Epi.CAPACETE));
                        procedimentoEpiDao.inserir();
                    }

                    JanelaLogin.connection.commit();

                    JOptionPane.showMessageDialog(null, "Procedimento cadastrado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, this.getTitle());
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Este procedimento já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void checkRequiredFields() {
        ((TextFieldValidator) jTextField2).validarCampo();
        ((FormatedFieldValidator) jFormattedTextField2).validarCampo();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jTextField2 = new TextFieldValidator(80, -1, true, true, "text", jLabel7);
        jFormattedTextField1 = new javax.swing.JFormattedTextField();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel10 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jCheckBox2 = new javax.swing.JCheckBox();
        jCheckBox3 = new javax.swing.JCheckBox();
        jCheckBox4 = new javax.swing.JCheckBox();
        jCheckBox5 = new javax.swing.JCheckBox();
        jPanel4 = new javax.swing.JPanel();
        jCheckBox6 = new javax.swing.JCheckBox();
        jCheckBox7 = new javax.swing.JCheckBox();
        jCheckBox8 = new javax.swing.JCheckBox();
        jCheckBox9 = new javax.swing.JCheckBox();
        jCheckBox10 = new javax.swing.JCheckBox();
        jFormattedTextField2 = new FormatedFieldValidator(true, true, "money", jLabel9);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Procedimentos");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(700, 320));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Procedimento");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(10, 20, 180, 14);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton2.setText("Cadastrar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2);
        jButton2.setBounds(10, 480, 100, 23);

        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton7.setText("Cancelar");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton7);
        jButton7.setBounds(120, 480, 100, 23);
        jPanel1.add(jTextField2);
        jTextField2.setBounds(10, 40, 545, 20);

        jFormattedTextField1.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        jFormattedTextField1.setEnabled(false);
        jPanel1.add(jFormattedTextField1);
        jFormattedTextField1.setBounds(560, 40, 109, 20);

        jCheckBox1.setBackground(Configurations.getBackGroundColor());
        jCheckBox1.setEnabled(false);
        jPanel1.add(jCheckBox1);
        jCheckBox1.setBounds(555, 17, 21, 21);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Prazo");
        jPanel1.add(jLabel8);
        jLabel8.setBounds(580, 20, 80, 14);

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel9.setText("Valor");
        jPanel1.add(jLabel9);
        jLabel9.setBounds(675, 20, 90, 14);

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Monospaced", 1, 9)); // NOI18N
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setWrapStyleWord(true);
        jScrollPane1.setViewportView(jTextArea1);
        jTextArea1.setDocument(new FixedLengthDocument(3500));

        jPanel1.add(jScrollPane1);
        jScrollPane1.setBounds(10, 85, 780, 300);

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel10.setText("Descrição Passo a Passo");
        jPanel1.add(jLabel10);
        jLabel10.setBounds(10, 65, 180, 14);

        jPanel2.setBackground(Configurations.getBackGroundColor());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Riscos "));
        jPanel2.setLayout(null);

        jCheckBox2.setBackground(Configurations.getBackGroundColor());
        jCheckBox2.setText("Choque");
        jPanel2.add(jCheckBox2);
        jCheckBox2.setBounds(20, 20, 63, 23);

        jCheckBox3.setBackground(Configurations.getBackGroundColor());
        jCheckBox3.setText("Queimadura");
        jPanel2.add(jCheckBox3);
        jCheckBox3.setBounds(160, 50, 83, 23);

        jCheckBox4.setBackground(Configurations.getBackGroundColor());
        jCheckBox4.setText("Queda");
        jPanel2.add(jCheckBox4);
        jCheckBox4.setBounds(160, 20, 57, 23);

        jCheckBox5.setBackground(Configurations.getBackGroundColor());
        jCheckBox5.setText("Queda de Objetos");
        jPanel2.add(jCheckBox5);
        jCheckBox5.setBounds(20, 50, 120, 23);

        jPanel1.add(jPanel2);
        jPanel2.setBounds(10, 390, 310, 80);

        jPanel4.setBackground(Configurations.getBackGroundColor());
        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("EPI"));
        jPanel4.setLayout(null);

        jCheckBox6.setBackground(Configurations.getBackGroundColor());
        jCheckBox6.setText("Bota");
        jPanel4.add(jCheckBox6);
        jCheckBox6.setBounds(20, 20, 47, 23);

        jCheckBox7.setBackground(Configurations.getBackGroundColor());
        jCheckBox7.setText("Cinto");
        jPanel4.add(jCheckBox7);
        jCheckBox7.setBounds(120, 20, 51, 23);

        jCheckBox8.setBackground(Configurations.getBackGroundColor());
        jCheckBox8.setText("Luva");
        jPanel4.add(jCheckBox8);
        jCheckBox8.setBounds(220, 20, 49, 23);

        jCheckBox9.setBackground(Configurations.getBackGroundColor());
        jCheckBox9.setText("Oculos");
        jPanel4.add(jCheckBox9);
        jCheckBox9.setBounds(20, 50, 70, 23);

        jCheckBox10.setBackground(Configurations.getBackGroundColor());
        jCheckBox10.setText("Capacete");
        jPanel4.add(jCheckBox10);
        jCheckBox10.setBounds(120, 50, 71, 23);

        jPanel1.add(jPanel4);
        jPanel4.setBounds(330, 390, 300, 80);
        jPanel1.add(jFormattedTextField2);
        jFormattedTextField2.setBounds(675, 40, 115, 20);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 800, 510);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 801, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 510, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        LinkedList<String> listaValidacao = validarCamposOrdemServico();
        if (listaValidacao.size() == 0) {
            if (idProcedimento == 0) {
                adicionarProcedimento();
            } else {
                editarProcedimento();
            }
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(listaValidacao), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton7ActionPerformed

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
    }//GEN-LAST:event_formComponentResized

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton7;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox10;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JCheckBox jCheckBox3;
    private javax.swing.JCheckBox jCheckBox4;
    private javax.swing.JCheckBox jCheckBox5;
    private javax.swing.JCheckBox jCheckBox6;
    private javax.swing.JCheckBox jCheckBox7;
    private javax.swing.JCheckBox jCheckBox8;
    private javax.swing.JCheckBox jCheckBox9;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JFormattedTextField jFormattedTextField2;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
